const http = require('http')
const url = require('url')

module.exports = () => {
  const taskList = []

  const server = http.createServer((req, res) => {
    let { pathname, query } = url.parse(req.url, true)
    // req.query = query

    res.send = data => {
      if (typeof data == 'string') {
        res.setHeader('Content-type', 'text/html;charset=utf-8')
        res.end(data)
      } else if (typeof data == 'object') {
        res.end(JSON.stringify(data))
      } else {
        throw new Error('解决不了')
      }
    }

    for (var i = 0; i < taskList.length; i++) {
      if (taskList[i].uri == pathname) {
        taskList[i].fn(req, res)
        break;
      }
    }
  })

  server.get = (uri, fn) => {
    taskList.push({ uri, fn })
  }

  return server;
}